package com.example.geoaimavlink_android.activity.view.obstacle

import android.content.Intent
import android.os.Bundle
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.geoaimavlink_android.R
import com.geoai.mavlink.geoainet.base.constant.GEOAIConstant
import com.geoai.mavlink.geoainet.base.mavlinkcore.controller.ProductManager
import com.geoai.mavlink.geoainet.base.mavlinkcore.controller.StarLinkClientManager
import com.geoai.mavlink.geoainet.base.mavlinkcore.engine.GEOAIError
import com.geoai.mavlink.geoainet.base.mavlinkcore.interfaces.CompletionCallback
import com.geoai.mavlink.geoainet.obstacle.enums.ObstacleCalibrationSource
import com.geoai.mavlink.geoainet.obstacle.enums.ObstacleCameraSource
import com.geoai.module.common.thread.ExecutorsManager
import kotlinx.android.synthetic.main.activity_obstacle_calibration.btn_hs_command_left
import kotlinx.android.synthetic.main.activity_obstacle_calibration.btn_hs_command_right
import kotlinx.android.synthetic.main.activity_obstacle_calibration.btn_qs_command_left
import kotlinx.android.synthetic.main.activity_obstacle_calibration.btn_qs_command_right
import kotlinx.android.synthetic.main.activity_obstacle_calibration.btn_ss_command_left
import kotlinx.android.synthetic.main.activity_obstacle_calibration.btn_ss_command_right
import kotlinx.android.synthetic.main.activity_obstacle_calibration.btn_xs_command_left
import kotlinx.android.synthetic.main.activity_obstacle_calibration.btn_xs_command_right
import kotlinx.android.synthetic.main.activity_obstacle_calibration.btn_ys_command_left
import kotlinx.android.synthetic.main.activity_obstacle_calibration.btn_ys_command_right
import kotlinx.android.synthetic.main.activity_obstacle_calibration.btn_zs_command_left
import kotlinx.android.synthetic.main.activity_obstacle_calibration.btn_zs_command_right
import kotlinx.android.synthetic.main.activity_obstacle_calibration.tv_fc_connection_status
import kotlinx.android.synthetic.main.activity_obstacle_calibration.tv_fc_sn
import kotlinx.android.synthetic.main.activity_obstacle_calibration.tv_fc_version
import kotlinx.android.synthetic.main.activity_obstacle_calibration.tv_obstacle_connection_status
import kotlinx.android.synthetic.main.activity_obstacle_calibration.tv_obstacle_version
import java.io.File

/**
 * @Author      : Ronny
 * @Email       : Ronny_xie@hotmail.com
 * @Date        : on 2024-05-31 10:52.
 * @Description :
 */
class ObstacleCalibrationActivity : AppCompatActivity() {

    private lateinit var OBSTACLE_FILE_PATH: String

    private var mFcSn: String? = null

    private var mProductID: String? = null

    private lateinit var mProductManager: ProductManager

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_obstacle_calibration)

        OBSTACLE_FILE_PATH = getExternalFilesDir("")?.path!! + File.separator + "ObstacleCalibration"

        initComponentVersion()

        initObstacleCalibrationFileStatus()

        initLeftButtonAction()

        initLeftButtonRemoveAction()

        initRightButtonAction()
    }

    private fun initLeftButtonRemoveAction() {
        btn_qs_command_left.setOnLongClickListener {
            val findObstacleFile = findObstacleFile("前视")
            findObstacleFile?.delete()
            true
        }
        btn_hs_command_left.setOnLongClickListener {
            val findObstacleFile = findObstacleFile("后视")
            findObstacleFile?.delete()
            true
        }
        btn_zs_command_left.setOnLongClickListener {
            val findObstacleFile = findObstacleFile("左视")
            findObstacleFile?.delete()
            true
        }
        btn_ys_command_left.setOnLongClickListener {
            val findObstacleFile = findObstacleFile("右视")
            findObstacleFile?.delete()
            true
        }
        btn_ss_command_left.setOnLongClickListener {
            val findObstacleFile = findObstacleFile("上视")
            findObstacleFile?.delete()
            true
        }
        btn_xs_command_left.setOnLongClickListener {
            val findObstacleFile = findObstacleFile("下视")
            findObstacleFile?.delete()
            true
        }
    }

    private fun initComponentVersion() {
        ExecutorsManager.get().executeAtFixedRate({
            //1s一次，判定当前无人机连接状态
            val productManagers = StarLinkClientManager.getInstance().productManager
            runOnUiThread {
                //无人机状态
                tv_fc_connection_status?.text = if (productManagers.isEmpty()) {
                    "未连接"
                } else {
                    "已连接"
                }
                //避障模块状态
                productManagers.forEach { (id, productManager) ->
                    mProductID = id.toString()
                    mProductManager = productManager
                    tv_obstacle_connection_status?.text = if (productManager.obstacleManager.isProductConnected) {
                        "已连接"
                    } else {
                        "未连接"
                    }
                    //版本号解析
                    productManager.systemManager.componentVersionInfo.forEach { (id, versionInfo) ->
                        if (id.toInt() == GEOAIConstant.MAVLINK_SYS_COMP_TYPE_FC) {
                            //飞控
                            tv_fc_version?.text = analyzeSoftWareVersionInfo(versionInfo.swVersionCode)
                        } else if (id.toInt() == GEOAIConstant.MAVLINK_SYS_HEARTBEAT_TYPE_OBSTACLE) {
                            //避障
                            tv_obstacle_version?.text = analyzeSoftWareVersionInfo(versionInfo.swVersionCode)
                        }
                    }
                    //sn解析
                    productManager.flyControllerManager.getSn(object : CompletionCallback.ICompletionCallbackWith<String>{
                        override fun onFailure(geoaiError: GEOAIError?) {
                            mFcSn = "unknown"
                            tv_fc_sn?.text = mFcSn
                        }

                        override fun onResult(sn: String) {
                            mFcSn = sn
                            tv_fc_sn?.text = mFcSn
                        }
                    })
                }
            }
        }, 1000, 1000)
    }

    private fun initObstacleCalibrationFileStatus() {
        //用来监控目录下的文件变化
        //目录规则：ObstacleCalibration/{FC_SN}/{前视_20240115163020_已上传.vc}
        ExecutorsManager.get().executeAtFixedRate({
            val file = File(OBSTACLE_FILE_PATH + File.separator + mFcSn)
            if (!file.exists()) {
                file.mkdirs()
            }
            val files = file.listFiles()
            configLeftTextView(null, btn_qs_command_left)
            configLeftTextView(null, btn_hs_command_left)
            configLeftTextView(null, btn_zs_command_left)
            configLeftTextView(null, btn_ys_command_left)
            configLeftTextView(null, btn_ss_command_left)
            configLeftTextView(null, btn_xs_command_left)
            if (files != null && files.isNotEmpty()) {
                files.forEach { obstacleFile ->
                    if (obstacleFile.name.contains("前视")) {
                        configLeftTextView(obstacleFile, btn_qs_command_left)
                    } else if (obstacleFile.name.contains("后视")) {
                        configLeftTextView(obstacleFile, btn_hs_command_left)
                    } else if (obstacleFile.name.contains("左视")) {
                        configLeftTextView(obstacleFile, btn_zs_command_left)
                    } else if (obstacleFile.name.contains("右视")) {
                        configLeftTextView(obstacleFile, btn_ys_command_left)
                    } else if (obstacleFile.name.contains("上视")) {
                        configLeftTextView(obstacleFile, btn_ss_command_left)
                    } else if (obstacleFile.name.contains("下视")) {
                        configLeftTextView(obstacleFile, btn_xs_command_left)
                    }
                }
            }
        }, 3000, 1000)
    }

    private fun initLeftButtonAction() {
        btn_qs_command_left?.setOnClickListener {
            if (mFcSn == null || mProductID == null) {
                return@setOnClickListener
            }
            findObstacleFile("前视")?.let {
                mProductManager.obstacleManager.uploadObstacleCalibrationFile(ObstacleCalibrationSource.OBSTACLE_CAMERA_FRONT, it.path) { geoaiError ->
                    if (geoaiError == null) {
                        it.renameTo(File(it.path.replace("未上传", "已上传")))
                    } else {
                        runOnUiThread {
                            Toast.makeText(
                                this@ObstacleCalibrationActivity,
                                "error: ${geoaiError.description}",
                                Toast.LENGTH_LONG
                            ).show()
                        }
                    }
                }
            }
        }
        btn_hs_command_left?.setOnClickListener {
            if (mFcSn == null || mProductID == null) {
                return@setOnClickListener
            }
            findObstacleFile("后视")?.let {
                mProductManager.obstacleManager.uploadObstacleCalibrationFile(ObstacleCalibrationSource.OBSTACLE_CAMERA_TAIL, it.path) { geoaiError ->
                    if (geoaiError == null) {
                        it.renameTo(File(it.path.replace("未上传", "已上传")))
                    } else {
                        runOnUiThread {
                            Toast.makeText(
                                this@ObstacleCalibrationActivity,
                                "error: ${geoaiError.description}",
                                Toast.LENGTH_LONG
                            ).show()
                        }
                    }
                }
            }
        }
        btn_zs_command_left?.setOnClickListener {
            if (mFcSn == null || mProductID == null) {
                return@setOnClickListener
            }
            findObstacleFile("左视")?.let {
                mProductManager.obstacleManager.uploadObstacleCalibrationFile(ObstacleCalibrationSource.OBSTACLE_CAMERA_LEFT, it.path) { geoaiError ->
                    if (geoaiError == null) {
                        it.renameTo(File(it.path.replace("未上传", "已上传")))
                    } else {
                        runOnUiThread {
                            Toast.makeText(
                                this@ObstacleCalibrationActivity,
                                "error: ${geoaiError.description}",
                                Toast.LENGTH_LONG
                            ).show()
                        }
                    }
                }
            }
        }
        btn_ys_command_left?.setOnClickListener {
            if (mFcSn == null || mProductID == null) {
                return@setOnClickListener
            }
            findObstacleFile("右视")?.let {
                mProductManager.obstacleManager.uploadObstacleCalibrationFile(ObstacleCalibrationSource.OBSTACLE_CAMERA_RIGHT, it.path) { geoaiError ->
                    if (geoaiError == null) {
                        it.renameTo(File(it.path.replace("未上传", "已上传")))
                    } else {
                        runOnUiThread {
                            Toast.makeText(
                                this@ObstacleCalibrationActivity,
                                "error: ${geoaiError.description}",
                                Toast.LENGTH_LONG
                            ).show()
                        }
                    }
                }
            }
        }
        btn_ss_command_left?.setOnClickListener {
            if (mFcSn == null || mProductID == null) {
                return@setOnClickListener
            }
            findObstacleFile("上视")?.let {
                mProductManager.obstacleManager.uploadObstacleCalibrationFile(ObstacleCalibrationSource.OBSTACLE_CAMERA_UP, it.path) { geoaiError ->
                    if (geoaiError == null) {
                        it.renameTo(File(it.path.replace("未上传", "已上传")))
                    } else {
                        runOnUiThread {
                            Toast.makeText(
                                this@ObstacleCalibrationActivity,
                                "error: ${geoaiError.description}",
                                Toast.LENGTH_LONG
                            ).show()
                        }
                    }
                }
            }
        }
        btn_xs_command_left?.setOnClickListener {
            if (mFcSn == null || mProductID == null) {
                return@setOnClickListener
            }
            findObstacleFile("下视")?.let {
                mProductManager.obstacleManager.uploadObstacleCalibrationFile(ObstacleCalibrationSource.OBSTACLE_CAMERA_DOWN, it.path) { geoaiError ->
                    if (geoaiError == null) {
                        it.renameTo(File(it.path.replace("未上传", "已上传")))
                    } else {
                        runOnUiThread {
                            Toast.makeText(
                                this@ObstacleCalibrationActivity,
                                "error: ${geoaiError.description}",
                                Toast.LENGTH_LONG
                            ).show()
                        }
                    }
                }
            }
        }
    }

    private fun initRightButtonAction() {
        btn_qs_command_right.setOnClickListener {
            if (mFcSn == null || mProductID == null) {
                return@setOnClickListener
            }
            if (findObstacleFile("前视") == null) {
                updateObstacleCameraMode("前视")
            }
        }
        btn_hs_command_right.setOnClickListener {
            if (mFcSn == null || mProductID == null) {
                return@setOnClickListener
            }
            if (findObstacleFile("后视") == null) {
                updateObstacleCameraMode("后视")
            }
        }
        btn_zs_command_right.setOnClickListener {
            if (mFcSn == null || mProductID == null) {
                return@setOnClickListener
            }
            if (findObstacleFile("左视") == null) {
                updateObstacleCameraMode("左视")
            }
        }
        btn_ys_command_right.setOnClickListener {
            if (mFcSn == null || mProductID == null) {
                return@setOnClickListener
            }
            if (findObstacleFile("右视") == null) {
                updateObstacleCameraMode("右视")
            }
        }
        btn_ss_command_right.setOnClickListener {
            if (mFcSn == null || mProductID == null) {
                return@setOnClickListener
            }
            if (findObstacleFile("上视") == null) {
                updateObstacleCameraMode("上视")
            }
        }
        btn_xs_command_right.setOnClickListener {
            if (mFcSn == null || mProductID == null) {
                return@setOnClickListener
            }
            if (findObstacleFile("下视") == null) {
                updateObstacleCameraMode("下视")
            }
        }
    }

    private fun updateObstacleCameraMode(mode: String) {
        val intent = Intent(this,CalibrationActivity::class.java)
        intent.putExtra("mode",mode)
        intent.putExtra("sn",mFcSn)
        intent.putExtra("id",mProductID)
        when (mode) {
            "前视" -> {
                mProductManager.obstacleManager.setObstacleCameraSource(ObstacleCameraSource.OBSTACLE_CAMERA_FRONT) {
                    if (it == null) {
                        startActivity(intent)
                    } else {
                        runOnUiThread {
                            Toast.makeText(this, "error: ${it.description}", Toast.LENGTH_LONG).show()
                        }
                    }
                }
            }
            "后视" -> {
                mProductManager.obstacleManager.setObstacleCameraSource(ObstacleCameraSource.OBSTACLE_CAMERA_TAIL) {
                    if (it == null) {
                        startActivity(intent)
                    } else {
                        runOnUiThread {
                            Toast.makeText(this, "error: ${it.description}", Toast.LENGTH_LONG).show()
                        }
                    }
                }
            }
            "左视" -> {
                mProductManager.obstacleManager.setObstacleCameraSource(ObstacleCameraSource.OBSTACLE_CAMERA_LEFT) {
                    if (it == null) {
                        startActivity(intent)
                    } else {
                        runOnUiThread {
                            Toast.makeText(this, "error: ${it.description}", Toast.LENGTH_LONG).show()
                        }
                    }
                }
            }
            "右视" -> {
                mProductManager.obstacleManager.setObstacleCameraSource(ObstacleCameraSource.OBSTACLE_CAMERA_RIGHT) {
                    if (it == null) {
                        startActivity(intent)
                    } else {
                        runOnUiThread {
                            Toast.makeText(this, "error: ${it.description}", Toast.LENGTH_LONG).show()
                        }
                    }
                }
            }
            "上视" -> {
                mProductManager.obstacleManager.setObstacleCameraSource(ObstacleCameraSource.OBSTACLE_CAMERA_UP) {
                    if (it == null) {
                        startActivity(intent)
                    } else {
                        runOnUiThread {
                            Toast.makeText(this, "error: ${it.description}", Toast.LENGTH_LONG).show()
                        }
                    }
                }
            }
            "下视" -> {
                mProductManager.obstacleManager.setObstacleCameraSource(ObstacleCameraSource.OBSTACLE_CAMERA_DOWN) {
                    if (it == null) {
                        startActivity(intent)
                    } else {
                        runOnUiThread {
                            Toast.makeText(this, "error: ${it.description}", Toast.LENGTH_LONG).show()
                        }
                    }
                }
            }
        }
    }

    private fun configLeftTextView(file: File?, leftTextView: TextView?) {
        val suffix = file?.name?.substring(file.name.lastIndexOf("_") + 1, file.name.lastIndexOf(".")) ?: ""
        runOnUiThread {
            when (suffix) {
                "已上传" -> {
                    leftTextView?.text = "已上传"
                    leftTextView?.setBackgroundResource(R.color.green)
                }
                "未上传" -> {
                    leftTextView?.text = "未上传"
                    leftTextView?.setBackgroundResource(R.color.orange)
                }
                else -> {
                    leftTextView?.text = "未校准"
                    leftTextView?.setBackgroundResource(R.color.red)
                }
            }
        }
    }

    private fun findObstacleFile(obName: String): File? {
        val files = File(OBSTACLE_FILE_PATH + File.separator + mFcSn + File.separator)
        if (files.isDirectory()) {
            files.listFiles()?.forEach { file ->
                if (file.name.contains(obName)) {
                    return file
                }
            }
        }
        return null
    }

    private fun analyzeSoftWareVersionInfo(s: Long): String {
        val major = (s shr 24).toInt()
        val minor = (s shr 16 and 0xff).toInt()
        val patch = (s shr 8 and 0xff).toInt()
        val type = (s and 0xff).toInt()
        return "$major.$minor.$patch.$type"
    }
}